const baseUrl = 'https://api.vinoyy.com';
// const baseUrl = 'http://localhost:3000';

const _http = ({ url, data, method }) => {
    wx.showLoading({
        title: '加载中',
    })

    return new Promise((resolve, reject) => {
        wx.request({
            url: baseUrl + url,
            data: data,
            header: _setHeader(),
            method: method || 'get',
            complete: (res) => {
                wx.hideLoading();
                if (res.data.code == 200) {
                    resolve(res.data)
                } 
                if (res.data.code == 1403) {
                    _errorHandler({ url, data, method, resolve })
                }
            }
        })
    })
}

/**
 * 设置请求头header
 */
const _setHeader = () => {
    return {
        'content-type': 'application/json',
        'X-WX-TOKEN': wx.getStorageSync('token')
    }
}

/**
 * 1403处理接口错误异常
 */
const _errorHandler = ({ url, data, method, resolve }) => {
    _wxLogin().then(() => {
        wx.request({
            url: baseUrl + url,
            data: data,
            header: _setHeader(),
            method: method || 'get',
            complete: (res) => {
                wx.hideLoading();
                if (res.data.code == 200) {
                    resolve(res.data)
                }
                if (res.data.code == 1403) {
                    _errorHandler({ url, data, method, resolve })
                }
            }
        })
    })
}

/**
 * get类型的网络请求
 */
const get = ({
    url,
    data,
    method
}) => {
    return _http({
        url,
        data
    })
}

/**
 * post类型的网络请求
 */
const post = (path, data = {}) => {
    return http({
        path,
        data,
        method: 'post',
        func
    })
}

/**
 * wx登录接口
 */
const _wxLogin = () => {
    return new Promise((resolve, reject) => {
        wx.login({
            success(res) {
                let params = {
                    url: '/wx/login', 
                    data: {
                        code: res.code
                    }
                }
                get(params).then(data => {
                    if (data.code == 200) {
                        let ret = data.data;
                        wx.setStorageSync('userid', ret.userid)
                        wx.setStorageSync('openid', ret.openid)
                        wx.setStorageSync('token', ret.token)
                    }
                    resolve();
                })
            }
        })
    })
}


module.exports = {
    get,
    post
}